package com.ruoyi.framework.config;

import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.ruoyi.framework.dataScope.DataAuthInterceptor;
import com.ruoyi.framework.dataScope.strategy.DataScopeContext;
import com.ruoyi.framework.tenant.BaseTenantHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * Mybatis支持*匹配扫描包
 *
 * @author ruoyi
 */
@EnableTransactionManagement
@Configuration
public class MyBatisConfig {

    @Autowired
    private BaseTenantHandler baseTenantHandler;
    @Autowired
    private DataScopeContext dataScopeContext;

    /**
     * 分页组件,自动识别数据库类型
     * 多租户，请参考官网【插件扩展】
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        List<ISqlParser> sqlParserList = new ArrayList<>();
        // 攻击 SQL 阻断解析器、加入解析链
        sqlParserList.add(new BlockAttackSqlParser());
        // 多租户拦截
        TenantSqlParser tenantSqlParser = new TenantSqlParser();
        tenantSqlParser.setTenantHandler(baseTenantHandler);
        sqlParserList.add(tenantSqlParser);
        paginationInterceptor.setSqlParserList(sqlParserList);
        return paginationInterceptor;
    }

    @Bean
    @ConditionalOnMissingBean
    public DataAuthInterceptor dataScopeInterceptor(DataSource dataSource) {
        return new DataAuthInterceptor();
    }
}